<script setup lang="ts">
import useUserStore from '@/store/modules/user';
import { pageAnswer } from '@/api/exam/answer';
import { useElTableHeight } from '@/utils/useElTableHeight';
import router from '@/router';

const userStore = useUserStore();

const getGreetings = () => {
  const hour = new Date().getHours();
  if (hour >= 6 && hour < 12) return '上午好';
  if (hour >= 12 && hour < 14) return '中午好';
  if (hour >= 14 && hour < 18) return '下午好';
  if (hour >= 18) return '晚上好';
  return '凌晨好';
};
const activeKey = ref('1');

const activeColumns = ref<any>([
  { title: '考试名称', dataIndex: ['project', 'name'], key: 'projectName', align: 'center' },
  { title: '开始时间', dataIndex: ['metaInfo', 'answerInfo', 'startTime'], key: 'startTime', align: 'center' },
  { title: '完成状态', dataIndex: 'tempSave', key: 'tempSave', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center' }
]);
const recordColumns = ref<any>([
  { title: '考试名称', dataIndex: ['project', 'name'], key: 'projectName', align: 'center' },
  { title: '开始时间', dataIndex: ['metaInfo', 'answerInfo', 'startTime'], key: 'startTime', align: 'center' },
  { title: '完成时间', dataIndex: ['metaInfo', 'answerInfo', 'endTime'], key: 'endTime', align: 'center' },
  { title: '完成状态', dataIndex: 'tempSave', key: 'tempSave', align: 'center' },
  { title: '答题用时', dataIndex: 'useTime', key: 'useTime', align: 'center' },
  { title: '我的得分', dataIndex: 'examScore', key: 'examScore', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center' }
]);
const activeQueryParams = ref({
  pageNum: 1,
  pageSize: 20,
  tempSave: '0',
  createBy: userStore.userId
});
const recordQueryParams = ref({
  pageNum: 1,
  pageSize: 20,
  tempSave: '1',
  createBy: userStore.userId
});
const loading = ref(false);
const activeList = ref([]);
const recordList = ref([]);
const activeTotal = ref(0);
const recordTotal = ref(0);
const getActiveList = async () => {
  loading.value = true;
  const res = await pageAnswer(activeQueryParams.value);
  activeList.value = res.rows;
  activeTotal.value = res.total;
  loading.value = false;
};
const getRecordList = async () => {
  loading.value = true;
  const res = await pageAnswer(recordQueryParams.value);
  recordList.value = res.rows;
  recordTotal.value = res.total;
  loading.value = false;
};

const timeDifference = (endTime, startTime) => {
  return formatTimeDifference((Date.parse(endTime) - Date.parse(startTime)) / 1000);
};

function formatTimeDifference(seconds) {
  // 确保输入是数字类型
  seconds = parseFloat(seconds);

  // 处理小于0的情况
  if (isNaN(seconds) || seconds < 0) {
    return '0秒';
  }

  // 计算分钟和剩余秒数
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  // 确保秒数始终显示为两位数字
  const formattedSeconds = remainingSeconds < 10 ?
    `0${remainingSeconds}` :
    remainingSeconds;

  return `${minutes} 分 ${formattedSeconds} 秒`;
}

//继续答题
const handleContinue = (id) => {
  const route = router.resolve({
    path: `/c/${id}`
  });
  window.open(route.href, '_blank');
};
const handlePreview = (id) => {
  const route = router.resolve({
    path: `/p/${id}`
  });
  window.open(route.href, '_blank');
};
onMounted(() => {
  getRecordList();
  getActiveList();
});
</script>

<template>
  <a-page-header title="首页">
    <a-card hoverable class="mb-2">
      <a-row :gutter="24">
        <a-col>
          <a-avatar :size="{ xs: 24, sm: 32, md: 40, lg: 64, xl: 80, xxl: 100 }">
            <template #icon>
              <img :src="userStore.avatar" class="user-avatar" />
            </template>
          </a-avatar>
        </a-col>
        <a-col>
          <h2> {{ getGreetings() }}, {{ userStore.nickname }}</h2>
        </a-col>
      </a-row>
    </a-card>
    <a-card hoverable ref="cardRef">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="我的考试">
          <a-table :columns="activeColumns" :data-source="activeList" :scroll="{x:'100%',y:  '200px'}"
                   :loading="loading" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'tempSave'">
                <span v-if="record.tempSave==='1'"> <a-badge status="success" />已完成</span>
                <span v-else> <a-badge status="processing" />进行中</span>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" @click="handleContinue(record.id)">继续答题</a-button>
              </template>
            </template>
          </a-table>
          <div ref="paginationRef" v-show="activeTotal>0">
            <pagination v-model:limit="activeQueryParams.pageSize" v-model:page="activeQueryParams.pageNum"
                        :total="activeTotal" @pagination="getActiveList" class="mt-5" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="考试记录">
          <a-table :columns="recordColumns" :data-source="recordList" :scroll="{x:'100%',y:  '200px'}"
                   :loading="loading" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'tempSave'">
                <span v-if="record.tempSave==='1'"> <a-badge status="success" />已完成</span>
                <span v-else> <a-badge status="processing" />进行中</span>
              </template>
              <template v-if="column.dataIndex === 'useTime'">
                {{ timeDifference(record.metaInfo.answerInfo.endTime, record.metaInfo.answerInfo.startTime) }}
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" @click="handlePreview(record.id)">查看答卷</a-button>
              </template>
            </template>
          </a-table>
          <div ref="paginationRef" v-show="recordTotal>0">
            <pagination v-model:limit="recordQueryParams.pageSize" v-model:page="recordQueryParams.pageNum"
                        :total="recordTotal" @pagination="getRecordList" class="mt-5" />
          </div>
        </a-tab-pane>
      </a-tabs>

    </a-card>
  </a-page-header>
</template>

<style scoped lang="scss">

</style>
